function [d,prob] = kstwo(data1,data2)

% function [d,prob] = KSTWO(data1,data2) computes the 
% Kolmogorov-Smirnov statistic d and the significance
% level prob for the null hypothesis that the data sets 
% data1 and data2 are drawn from the same distribution.
% Small values of prob show that the cumulative distribution
% function of data1 is significantly different from that
% of data2. Adapted from Press, Teukolsky, Vetterling
% and Flannery, Numerical Recipes in Fortran p619.
% Uses PROBKS

% Version 1.0 RHS 8/11/93

data1=sort(data1);data2=sort(data2);	% sort in ascending order

d1len=length(data1);d2len=length(data2); % number of points in data1 and data2

k1=1;k2=1;fn1=0;fn2=0;count=1;		% initialise variables
dt=NaN*zeros(max(d1len, d2len), 1);
while k1<=d1len && k2<=d2len		% generate cumulative distribution
	d1=data1(k1);d2=data2(k2);	% functions
	if d1<=d2
		fn1=k1/d1len;
		k1=k1+1;
	end
	if d2<=d1
		fn2=k2/d2len;
		k2=k2+1;
	end
	dt(count)=abs(fn1-fn2);		% difference between functions
	count=count+1;
end
d=max(dt);				% maximum of difference
N=sqrt(d1len*d2len/(d1len+d2len));
prob=probks((N+0.12+0.11/N)*d);		% calculate probability